<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人中心 - GoZero 聊天</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4F46E5',
                        secondary: '#818CF8',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .modern-gradient {
                background: linear-gradient(135deg, #e0e7ff 0%, #f8fafc 100%);
            }
            .modern-card {
                @apply rounded-2xl shadow-xl bg-white/90 backdrop-blur-md;
            }
            .modern-nav {
                background: linear-gradient(90deg, #6366f1 0%, #818cf8 100%);
                @apply shadow-lg backdrop-blur-md;
            }
            .stat-card {
                @apply bg-white rounded-xl p-4 shadow-md hover:shadow-lg transition-shadow;
            }
            .modern-btn {
                @apply rounded-full shadow-md bg-gradient-to-r from-primary to-secondary text-white font-semibold transition-all duration-200 px-4 py-2;
            }
            .modern-btn:hover {
                @apply from-secondary to-primary scale-105 shadow-lg;
            }
        }
    </style>
    <script src="/static/common.js"></script>
</head>
<body class="modern-gradient font-sans text-dark">
    <div class="min-h-screen flex flex-col">
        <!-- 顶部导航栏 -->
        <header class="modern-nav text-white shadow-md">
            <div class="container mx-auto px-4 py-3 flex justify-between items-center">
                <h1 class="text-xl font-bold flex items-center">
                    <i class="fa fa-comments-o mr-2"></i>GoZero 聊天
                </h1>
                <div class="flex items-center space-x-4">
                    <a href="/" class="bg-white text-primary px-3 py-1 rounded text-sm hover:bg-gray-100 transition-colors flex items-center">
                        <i class="fa fa-home mr-1"></i>首页
                    </a>
                    <!-- 顶部右侧登录/退出按钮 -->
                    <button id="auth-btn" class="modern-btn px-4 py-2"></button>
                </div>
            </div>
        </header>

        <main class="flex-grow container mx-auto px-4 py-10">
            <div class="max-w-5xl mx-auto">
                <div id="login-section" class="flex flex-col items-center justify-center min-h-[60vh] hidden">
                    <div class="modern-card p-8 flex flex-col items-center w-full max-w-sm">
                        <h2 class="text-2xl font-bold text-primary mb-6 flex items-center"><i class="fa fa-user-circle mr-2"></i>用户登录</h2>
                        <input id="login-username" class="modern-input w-full mb-4" type="text" placeholder="请输入用户名">
                        <button id="login-confirm-btn" class="modern-btn px-6 py-2 w-full">登录</button>
                    </div>
                </div>
                <div id="profile-section">
                    <!-- 用户信息美化卡片 -->
                    <div class="modern-card bg-gradient-to-br from-indigo-100 to-white rounded-2xl shadow-xl p-8 flex flex-col items-center max-w-lg mx-auto mb-8" id="profile-info-card">
                        <img id="profile-avatar" src="https://cdn.jsdelivr.net/gh/identicons/jasonlong.png" class="w-28 h-28 rounded-full shadow-lg mb-4 border-4 border-white" onerror="this.style.display='none'">
                        <div class="font-bold text-2xl text-primary mb-1" id="profile-username">昵称</div>
                        <div class="text-xs text-gray-400 mb-4" id="profile-userid">ID: 123456</div>
                        <div class="flex flex-wrap justify-center gap-4 w-full mb-4">
                            <div class="flex flex-col items-center bg-white/80 rounded-xl shadow p-4 min-w-[90px] hover:scale-105 transition">
                                <i class="fa fa-user text-primary mb-1"></i>
                                <div class="text-lg font-bold text-indigo-600" id="profile-friendcount">0</div>
                                <div class="text-xs text-gray-500 mt-1">好友数</div>
                            </div>
                            <div class="flex flex-col items-center bg-white/80 rounded-xl shadow p-4 min-w-[90px] hover:scale-105 transition">
                                <i class="fa fa-comments text-primary mb-1"></i>
                                <div class="text-lg font-bold text-indigo-600" id="profile-roomcount">0</div>
                                <div class="text-xs text-gray-500 mt-1">房间数</div>
                            </div>
                            <div class="flex flex-col items-center bg-white/80 rounded-xl shadow p-4 min-w-[90px] hover:scale-105 transition">
                                <i class="fa fa-star text-yellow-400 mb-1"></i>
                                <div class="text-lg font-bold text-indigo-600" id="profile-level">1</div>
                                <div class="text-xs text-gray-500 mt-1">等级</div>
                            </div>
                            <div class="flex flex-col items-center bg-white/80 rounded-xl shadow p-4 min-w-[90px] hover:scale-105 transition">
                                <i class="fa fa-circle text-green-400 mb-1" id="profile-status-icon"></i>
                                <div class="text-lg font-bold text-indigo-600" id="profile-status">在线</div>
                                <div class="text-xs text-gray-500 mt-1">在线状态</div>
                            </div>
                            <div class="flex flex-col items-center bg-white/80 rounded-xl shadow p-4 min-w-[90px] hover:scale-105 transition">
                                <i class="fa fa-calendar text-primary mb-1"></i>
                                <div class="text-lg font-bold text-indigo-600" id="profile-created">-</div>
                                <div class="text-xs text-gray-500 mt-1">注册时间</div>
                            </div>
                        </div>
                        <!-- 退出按钮已移至顶部，仅保留一个 -->
                    </div>

                        <!-- 统计信息卡片 -->
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                            <div class="stat-card">
                                <div class="flex items-center justify-between">
                                    <h3 class="text-lg font-semibold text-gray-700">好友数</h3>
                                    <i class="fa fa-users text-primary text-xl"></i>
                                </div>
                                <p id="profile-friendcount" class="text-3xl font-bold text-primary mt-2">-</p>
                                <p class="text-sm text-gray-500 mt-1">活跃好友</p>
                            </div>
                            <div class="stat-card">
                                <div class="flex items-center justify-between">
                                    <h3 class="text-lg font-semibold text-gray-700">房间数</h3>
                                    <i class="fa fa-comments text-secondary text-xl"></i>
                                </div>
                                <p id="profile-roomcount" class="text-3xl font-bold text-secondary mt-2">-</p>
                                <p class="text-sm text-gray-500 mt-1">创建的房间</p>
                            </div>
                            <div class="stat-card">
                                <div class="flex items-center justify-between">
                                    <h3 class="text-lg font-semibold text-gray-700">在线时长</h3>
                                    <i class="fa fa-clock-o text-green-500 text-xl"></i>
                                </div>
                                <p id="profile-onlinetime" class="text-3xl font-bold text-green-500 mt-2">-</p>
                                <p class="text-sm text-gray-500 mt-1">本周在线时长</p>
                            </div>
                        </div>

                        <!-- 最近活动 -->
                        <div class="modern-card p-6 mb-8">
                            <h3 class="text-xl font-semibold mb-4 flex items-center">
                                <i class="fa fa-history mr-2 text-primary"></i>最近活动
                            </h3>
                            <div id="recent-activities" class="space-y-4">
                                <!-- 活动列表将通过JavaScript动态生成 -->
                            </div>
                        </div>

                        <!-- 我的房间 -->
                        <div class="modern-card p-6">
                            <h3 class="text-xl font-semibold mb-4 flex items-center">
                                <i class="fa fa-th-large mr-2 text-primary"></i>我的房间
                            </h3>
                            <div id="my-rooms" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <!-- 房间列表将通过JavaScript动态生成 -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- 编辑资料模态框 -->
    <div id="edit-profile-modal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
        <div class="modern-card max-w-md w-full p-6">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">编辑个人资料</h3>
                <button id="close-modal-btn" class="text-gray-500 hover:text-gray-700">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                    <input type="text" id="edit-username" class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">个性签名</label>
                    <textarea id="edit-bio" class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-primary" rows="3"></textarea>
                </div>
            </div>
            <div class="flex justify-end space-x-3 mt-6">
                <button id="cancel-edit-btn" class="px-4 py-2 text-gray-600 hover:text-gray-800">取消</button>
                <button id="save-profile-btn" class="modern-btn">保存</button>
            </div>
        </div>
    </div>

    <!-- Toast提示 -->
    <div id="toast" class="fixed top-6 right-6 z-50 hidden"></div>

    <script>
        // 全局变量
        let currentUser = getCurrentUser();
        let onlineTimer = null;
        let startTime = null;

        // 渲染个人信息
        function renderProfile() {
            if (!currentUser) return;
            document.getElementById('profile-username').textContent = currentUser.username;
            document.getElementById('profile-userid').textContent = currentUser.userId;

            // 获取注册时间
            fetch(`/api/userinfo?user_id=${currentUser.userId}`)
                .then(res => {
                    if (!res.ok) return null;
                    return res.json();
                })
                .then(data => {
                    if (!data || data.error) {
                        document.getElementById('profile-created').textContent = '-';
                        return;
                    }
                    let created = data.created_at;
                    let dateObj = null;
                    if (typeof created === 'number') {
                        dateObj = new Date(created * 1000);
                    } else if (typeof created === 'string') {
                        dateObj = new Date(created);
                    }
                    document.getElementById('profile-created').textContent = dateObj && !isNaN(dateObj) ? dateObj.toLocaleString() : '';
                });

            // 好友数
            fetch(`/api/friends?user_id=${currentUser.userId}`)
                .then(res => res.ok ? res.json() : [])
                .then(ids => {
                    document.getElementById('profile-friendcount').textContent = Array.isArray(ids) ? ids.length : 0;
                });

            // 房间数
            fetch('/api/rooms')
                .then(res => res.ok ? res.json() : [])
                .then(rooms => {
                    rooms = Array.isArray(rooms) ? rooms : [];
                    let myRooms = rooms.filter(r => r && r.creator_id === currentUser.userId);
                    document.getElementById('profile-roomcount').textContent = myRooms.length;
                    renderMyRooms(myRooms);
                });

            // 更新在线时长
            updateOnlineTime();
            // 获取最近活动
            renderRecentActivities();
        }

        // 渲染我的房间
        function renderMyRooms(rooms) {
            const container = document.getElementById('my-rooms');
            container.innerHTML = '';
            
            if (rooms.length === 0) {
                container.innerHTML = '<div class="col-span-2 text-center text-gray-500 py-8">还没有创建过房间</div>';
                return;
            }

            rooms.forEach(room => {
                const card = document.createElement('div');
                card.className = 'bg-white rounded-lg p-4 shadow hover:shadow-md transition-shadow';
                card.innerHTML = `
                    <div class="flex items-center justify-between mb-2">
                        <h4 class="font-semibold">${room.name}</h4>
                        <span class="text-sm text-gray-500">${room.user_count}人在线</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-xs text-gray-500">创建于 ${new Date(room.created_at).toLocaleDateString()}</span>
                        <button class="text-primary hover:text-secondary text-sm" onclick="window.location.href='/static/index.html'">
                            <i class="fa fa-sign-in mr-1"></i>进入
                        </button>
                    </div>
                `;
                container.appendChild(card);
            });
        }

        // 更新在线时长
        function updateOnlineTime() {
            if (!startTime) {
                startTime = new Date();
            }
            const now = new Date();
            const diff = Math.floor((now - startTime) / 1000); // 秒
            const hours = Math.floor(diff / 3600);
            const minutes = Math.floor((diff % 3600) / 60);
            document.getElementById('profile-onlinetime').textContent = `${hours}h ${minutes}m`;
        }

        // 获取最近活动
        function renderRecentActivities() {
            // 模拟最近活动数据
            const activities = [
                { type: 'join', room: '交友聊天室', time: new Date() - 1000 * 60 * 5 },
                { type: 'create', room: '游戏房间', time: new Date() - 1000 * 60 * 30 },
                { type: 'friend', user: '张三', time: new Date() - 1000 * 60 * 60 },
            ];

            const container = document.getElementById('recent-activities');
            container.innerHTML = '';

            activities.forEach(activity => {
                const item = document.createElement('div');
                item.className = 'flex items-center space-x-3 text-sm';
                
                let icon, text;
                switch (activity.type) {
                    case 'join':
                        icon = 'fa-sign-in text-green-500';
                        text = `加入了房间 "${activity.room}"`;
                        break;
                    case 'create':
                        icon = 'fa-plus-circle text-blue-500';
                        text = `创建了房间 "${activity.room}"`;
                        break;
                    case 'friend':
                        icon = 'fa-user-plus text-purple-500';
                        text = `添加了好友 "${activity.user}"`;
                        break;
                }

                item.innerHTML = `
                    <i class="fa ${icon}"></i>
                    <span>${text}</span>
                    <span class="text-gray-500">${formatTime(activity.time)}</span>
                `;
                container.appendChild(item);
            });
        }

        // 格式化时间
        function formatTime(time) {
            const date = new Date(time);
            const now = new Date();
            const diff = Math.floor((now - date) / 1000);
            
            if (diff < 60) return '刚刚';
            if (diff < 3600) return `${Math.floor(diff / 60)}分钟前`;
            if (diff < 86400) return `${Math.floor(diff / 3600)}小时前`;
            return date.toLocaleDateString();
        }

        // 编辑资料相关
        const editProfileBtn = document.getElementById('edit-profile-btn');
        const editProfileModal = document.getElementById('edit-profile-modal');
        const closeModalBtn = document.getElementById('close-modal-btn');
        const cancelEditBtn = document.getElementById('cancel-edit-btn');
        const saveProfileBtn = document.getElementById('save-profile-btn');

        if (editProfileBtn) {
            editProfileBtn.onclick = () => {
                editProfileModal.classList.remove('hidden');
                document.getElementById('edit-username').value = currentUser.username;
            };
        }

        [closeModalBtn, cancelEditBtn].forEach(btn => {
            if (btn) {
                btn.onclick = () => {
                    editProfileModal.classList.add('hidden');
                };
            }
        });

        if (saveProfileBtn) {
            saveProfileBtn.onclick = () => {
                const newUsername = document.getElementById('edit-username').value.trim();
                if (!newUsername) {
                    showToast('用户名不能为空', 'error');
                    return;
                }
                // TODO: 调用后端API更新用户信息
                currentUser.username = newUsername;
                localStorage.setItem('gozero_chat_user', JSON.stringify(currentUser));
                editProfileModal.classList.add('hidden');
                renderProfile();
                showToast('保存成功', 'success');
            };
        }
        // 退出按钮逻辑
        if (document.getElementById('logout-btn')) {
            document.getElementById('logout-btn').onclick = function() {
                logoutAndRedirect();
            };
        }
        if (document.getElementById('mobile-logout-btn')) {
            document.getElementById('mobile-logout-btn').onclick = function() {
                logoutAndRedirect();
            };
        }

        // 页面加载时初始化
        window.addEventListener('DOMContentLoaded', () => {
            const userStr = localStorage.getItem('gozero_chat_user');
            if (userStr) {
                try {
                    currentUser = JSON.parse(userStr);
                    if (currentUser && currentUser.username) {
                        document.getElementById('login-section').classList.add('hidden');
                        document.getElementById('profile-section').classList.remove('hidden');
                        renderProfile();
                        onlineTimer = setInterval(updateOnlineTime, 60000);
                        updateAuthBtn(true);
                    } else {
                        showLoginOnly();
                    }
                } catch (e) {
                    currentUser = null;
                    showLoginOnly();
                }
            } else {
                showLoginOnly();
            }
            // 登录按钮事件
            const loginBtn = document.getElementById('login-confirm-btn');
            if (loginBtn) {
                loginBtn.onclick = function() {
                    const username = document.getElementById('login-username').value.trim();
                    if (!username) {
                        showToast('请输入用户名', 'error');
                        return;
                    }
                    // 调用后端登录接口
                    fetch('/api/login', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ username })
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.error) {
                            showToast(data.error, 'error');
                            return;
                        }
                        // 只用后端返回的 user_id 和 username
                        localStorage.setItem('gozero_chat_user', JSON.stringify({ userId: data.user_id, username: username }));
                        currentUser = { userId: data.user_id, username: username };
                        document.getElementById('login-section').classList.add('hidden');
                        document.getElementById('profile-section').classList.remove('hidden');
                        renderProfile();
                        updateAuthBtn(true);
                        showToast(data.message || '登录成功', 'success');
                    })
                    .catch(() => {
                        showToast('登录失败，请重试', 'error');
                    });
                };
            }
        });

        // 只显示登录表单和提示
        function showLoginOnly() {
            document.getElementById('login-section').classList.remove('hidden');
            document.getElementById('profile-section').classList.add('hidden');
            updateAuthBtn(false);
        }

        // 顶部登录/退出按钮逻辑
        function updateAuthBtn(loggedIn) {
            const authBtn = document.getElementById('auth-btn');
            if (!authBtn) return;
            if (loggedIn) {
                authBtn.innerHTML = '<i class="fa fa-sign-out mr-1"></i>退出';
                authBtn.onclick = function() {
                    logoutAndRedirect('/static/profile.html');
                    updateAuthBtn(false);
                };
            } else {
                authBtn.innerHTML = '<i class="fa fa-sign-in mr-1"></i>登录';
                authBtn.onclick = function() {
                    // 显示登录表单并聚焦
                    document.getElementById('login-section').classList.remove('hidden');
                    document.getElementById('profile-section').classList.add('hidden');
                    const input = document.getElementById('login-username');
                    if (input) input.focus();
                };
            }
        }

        // 页面关闭时清理
        window.addEventListener('beforeunload', () => {
            if (onlineTimer) {
                clearInterval(onlineTimer);
            }
        });
    </script>
</body>
</html>
